package com.xmkj.carwash;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.common.adapter.helper.IRecyclerViewHelper;
import com.common.carbean.CanShuBean;
import com.common.carbean.CarListBean;
import com.common.carbean.MoneyBean;
import com.common.carbean.OrderIdBean;
import com.common.carbean.StatusBean;
import com.common.cons.Constans;
import com.common.location.LocationSubscriber;
import com.common.location.LocationUtils;
import com.common.location.RxLocation;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.entity.bean.DotsInfoBean;
import com.common.retrofit.methods.CheckOrderMethods;
import com.common.retrofit.methods.GetDotsMethods;
import com.common.retrofit.methods.GetsysparaMethods;
import com.common.retrofit.methods.GoOrderMethods;
import com.common.retrofit.methods.QuaryFreeMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.LogUtils;
import com.common.utils.SPUtils;
import com.common.utils.SizeUtils;
import com.common.widget.DividerDecoration.MarginDecoration;
import com.common.widget.recyclerview.refresh.adapter.CommonAdapter;
import com.common.widget.recyclerview.refresh.recycleview.XRecyclerView;
import com.xmkj.carwash.activity.ChooseCarActivity;
import com.xmkj.carwash.activity.MessageListActivity;
import com.xmkj.carwash.activity.OrderDetalActivitiy;
import com.xmkj.carwash.activity.OrderInfoActivity;
import com.xmkj.carwash.activity.PayActivity;
import com.xmkj.carwash.adapter.MapCityListAdapter;
import com.xmkj.carwash.bean.CityResultBean;
import com.xmkj.carwash.bean.TestData;
import com.xmkj.carwash.count.LoginActivtiy;
import com.xmkj.carwash.mine.activity.MineActivity;
import com.xmkj.carwash.utils.BottomPickerUtils;
import com.xmkj.carwash.utils.KeyBordUtil;
import com.xmkj.carwash.utils.SensorEventHelper;
import com.xmkj.carwash.utils.StatusBarUtil;
import com.xmkj.carwash.utils.ViewToBitmap;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

public class MainActivity extends BaseMvpActivity implements AMap.OnMarkerClickListener, LocationSource, AMap.OnCameraChangeListener, AMapLocationListener, PoiSearch.OnPoiSearchListener, TextWatcher, Inputtips.InputtipsListener {
    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.iv_mine)
    ImageView mIvMine;
    @BindView(R.id.iv_qustion)
    ImageView mIvQustion;
    @BindView(R.id.tv_now)
    TextView mTvNow;
    @BindView(R.id.tv_order)
    TextView mTvOrder;
    @BindView(R.id.iv_one)
    ImageView mIvOne;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.iv_two)
    ImageView mIvTwo;
    @BindView(R.id.tv_car)
    TextView mTvCar;
    @BindView(R.id.iv_three)
    ImageView mIvThree;
    @BindView(R.id.et_fujia)
    EditText et_fujia;
    @BindView(R.id.ll_now)
    LinearLayout mLlNow;
    @BindView(R.id.iv_order_one)
    ImageView mIvOrderOne;
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;
    @BindView(R.id.iv_order_two)
    ImageView mIvOrderTwo;
    @BindView(R.id.tv_order_adress)
    TextView mTvOrderAdress;
    @BindView(R.id.iv_order_three)
    ImageView mIvOrderThree;
    @BindView(R.id.tv_order_car)
    TextView mTvOrderCar;
    @BindView(R.id.iv_order_four)
    ImageView mIvOrderFour;
    @BindView(R.id.et_order_fujia)
    EditText et_order_fujia;
    @BindView(R.id.ll_order)
    LinearLayout mLlOrder;
    @BindView(R.id.ll_main)
    LinearLayout mLlMain;
    @BindView(R.id.tv_wash_money)
    TextView mTvWashMoney;
    @BindView(R.id.tv_call)
    TextView mTvCall;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.rl_choose_car)
    RelativeLayout rl_choose_car;
    @BindView(R.id.rl_choose_order_car)
    RelativeLayout rl_choose_order_car;
    @BindView(R.id.rl_choose_time)
    RelativeLayout rl_choose_time;
    @BindView(R.id.search_et_input)
    AutoCompleteTextView searchEtInput;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
    @BindView(R.id.rl_title)
    RelativeLayout rl_title;


    private AMap aMap;
    private SensorEventHelper mSensorHelper;
    private UiSettings uiSettings;
    private boolean mFirstFix = false;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker mLocMarker;
    //中心点的经纬度
    private double centerLatitude = 0;
    private double centerLongitude = 0;
    private int nowCarId;
    private boolean isNow = true;
    private int orderCarId;
    private String time;
    private String city = "杭州";
    private String nowmoney;
    private String ordermoney;
    private double latitude = 0;
    private double longitude = 0;
    private String currentCity;
    private PoiSearch.Query query;
    private PoiSearch poiSearch;
    private PoiResult poiResult;
    private ArrayList<PoiItem> poiItems;
    private String current;
    private String keyword = "";
    private String poiSearchType = "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施"; //搜索条件
    private MapCityListAdapter adapter;
    private String postLati = "";
    private String postLong = "";
    private StatusBean infoBean;
    private String reallAdress = "";
    private String detailsPlace;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onViewCreated() {
        Bundle saveInstanceState = getSaveInstanceState();
        mapView.onCreate(saveInstanceState);
    }

    @Override
    protected void doLogicFunc() {

        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.ORDER_STATUS_CHANGE) && (Boolean) rxKeyEvent.getValue()) {
                    gotoCheckOrder();

                }
            }
        }));

        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.NOW_CHOOSE_CAR) && EmptyUtils.isNotEmpty(rxKeyEvent.getValue())) {
                    CarListBean.ListsEntity infobean = (CarListBean.ListsEntity) rxKeyEvent.getValue();
                    if (isNow) {
                        mTvCar.setText(infobean.brand + " " + infobean.model + " " + infobean.carnum);
                        nowCarId = infobean.id;
                    } else {
                        mTvOrderCar.setText(infobean.brand + " " + infobean.model + " " + infobean.carnum);
                        orderCarId = infobean.id;

                    }
                    gotoQuaryFree();


                }
            }
        }));
        getPermission();
        initMap();
        attachClickListener(mIvMine);
        attachClickListener(mIvQustion);
        attachClickListener(ivMessage);
        attachClickListener(mTvNow);
        attachClickListener(mTvOrder);
        attachClickListener(rl_choose_car);
        attachClickListener(rl_choose_order_car);
        attachClickListener(rl_choose_time);
        attachClickListener(mTvCall);
        attachClickListener(mTvAddress);
        attachClickListener(mTvOrderAdress);
        attachClickListener(mTvLocation);
        attachClickListener(mIvLocation);
        setListener();

        mPageIndex = 0;
        setRecyclerView();
        //todo  后面加
        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constans.HASHID))) {
            gotoCheckOrder();
        }


        getLocation();
    }

/*    private void getOrderMoney() {
        CommonSubscriber<MoneyBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                MoneyBean infoBean = (MoneyBean) o;
                if (isNow) {
                    nowmoney = infoBean.money;
                    mTvWashMoney.setText("洗车费用：" + nowmoney + "元");
                } else {
                    ordermoney = infoBean.money;
                    mTvWashMoney.setText("洗车费用：" + ordermoney + "元");
                }


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        QuaryFreeMethods.getInstance().orderfee(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID), isNow ? nowCarId : orderCarId, city);
        rxManager.add(subscriber);
    }*/

    private void setRecyclerView() {
        adapter = new MapCityListAdapter(context, list);
        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 10), true));

        recyclerview.setHasFixedSize(true);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new CommonAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(CommonAdapter adapter, View view, int position) {
                CityResultBean bean = (CityResultBean) adapter.mData.get(position);
                if (view.getId() == R.id.ll_address) {
                    //隐藏键盘  editext  还有 recelerview
                    recyclerview.setVisibility(View.GONE);
                    searchEtInput.setVisibility(View.GONE);
                    rl_title.setVisibility(View.VISIBLE);
                    postLati = bean.latLonPoint.getLatitude() + "";
                    postLong = bean.latLonPoint.getLongitude() + "";
                    reallAdress = bean.getDetail();
                    if (isNow) {
                        mTvAddress.setText(bean.getDetail());
                    } else {
                        mTvOrderAdress.setText(bean.getDetail());
                    }
                }
            }
        });

        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mPageIndex = 0;
                mIsRefreshOrLoadMore = 0;
                doSearchQuery(keyword);
            }

            @Override
            public void onLoadMore() {
                if (mIsHasNoData) {
                    recyclerview.loadMoreComplete();
                    recyclerview.setNoMore(true);
                    return;
                }
                mPageIndex++;
                mIsRefreshOrLoadMore = 1;
                doSearchQuery(keyword);
            }
        });

    }

    private void setListener() {
        searchEtInput.addTextChangedListener(this);// 添加文本输入框监听事件

        searchEtInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    KeyBordUtil.hideSoftKeyboard(searchEtInput);
                    keyword = searchEtInput.getText().toString();

                    doSearchQuery(searchEtInput.getText().toString());
                    return true;
                }
                return false;
            }
        });
    }

    private void gotoCheckOrder() {

        CommonSubscriber<StatusBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                infoBean = (StatusBean) o;
                dismissProgressDialog();
                if ("4".equals(infoBean.status)) {
                    showDialog(infoBean);
                } else {
                    if (builder != null && builder.isShowing()) {
                        builder.dismiss();
                    }
                }
                switch (infoBean.status) {
                    case "1":
                        mTvCall.setText("待接单");
                        break;
                    case "2":
                        mTvCall.setText("在路上");
                        break;
                    case "3":
                        mTvCall.setText("洗车中");
                        break;
                    default:
                        mTvCall.setText("呼叫洗车");
                        break;
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        CheckOrderMethods.getInstance().orderinfo(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID));
        rxManager.add(subscriber);
    }

    private void gotoQuaryFree() {
        CommonSubscriber<MoneyBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                MoneyBean infoBean = (MoneyBean) o;
                if (isNow) {
                    nowmoney = infoBean.money;
                    mTvWashMoney.setText("洗车费用：" + nowmoney + "元");
                } else {
                    ordermoney = infoBean.money;
                    mTvWashMoney.setText("洗车费用：" + ordermoney + "元");
                }


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        QuaryFreeMethods.getInstance().orderfee(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID), isNow ? nowCarId : orderCarId, city);
        rxManager.add(subscriber);
    }

    public void showDialog(final StatusBean infoBean) {
        showOneDialog("提示", "你有一笔订单没支付", "去支付");
        setOnDialogViewClick(new OnDialogViewClick() {
            @Override
            public void leftViewClick() {

            }

            @Override
            public void singleViewClick() {
//                showToastMsg("我被点击了");
          /*      Intent intent = new Intent(context, PayActivity.class);
                intent.putExtra(PayActivity.ORDER_INFO, infoBean);
                startActivity(intent);*/

                Intent intent = new Intent(context, PayActivity.class);
                intent.putExtra(PayActivity.TOTAL, infoBean.total);
                intent.putExtra(PayActivity.ORDERID, infoBean.id + "");
                startActivity(intent);


            }
        });
        if (builder != null) {
            builder.setCanceledOnTouchOutside(false);
            builder.setCancelable(false);
        }
    }

    @Override
    protected void onViewClicked(View view) {
        super.onViewClicked(view);
        if (EmptyUtils.isEmpty(SPUtils.getShareString(Constans.HASHID))) {
            gotoActivity(LoginActivtiy.class);
            return;
        }
        if (view.getId() == mIvQustion.getId()) {
            gotoActivity(MineActivity.class);

        } else if (view.getId() == mIvMine.getId()) {
            getQuesTion();
        } else if (view.getId() == ivMessage.getId()) {
            gotoActivity(MessageListActivity.class);
        } else if (view.getId() == mTvNow.getId()) { // 现在
            isNow = true;
            mTvNow.setTextColor(context.getResources().getColor(R.color.main_color));
            mTvNow.setTextSize(18);
            mTvOrder.setTextColor(context.getResources().getColor(R.color.home_grey));
            mTvOrder.setTextSize(14);
            mLlNow.setVisibility(View.VISIBLE);
            mLlOrder.setVisibility(View.GONE);
        } else if (view.getId() == mTvOrder.getId()) {//预约
            isNow = false;
            mTvOrder.setTextColor(context.getResources().getColor(R.color.main_color));
            mTvOrder.setTextSize(18);
            mTvNow.setTextColor(context.getResources().getColor(R.color.home_grey));
            mTvNow.setTextSize(14);
            mLlNow.setVisibility(View.GONE);
            mLlOrder.setVisibility(View.VISIBLE);
        } else if (view.getId() == rl_choose_car.getId()) {
            gotoActivity(ChooseCarActivity.class);
        } else if (view.getId() == rl_choose_order_car.getId()) {
            gotoActivity(ChooseCarActivity.class);
        } else if (view.getId() == rl_choose_time.getId()) {
            Calendar startTime = Calendar.getInstance();
            int year = startTime.get(Calendar.YEAR);    //获取年
            int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
            int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            startTime.set(year, month, day);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2099, 0, 1);
            Calendar selectTime = Calendar.getInstance();
            MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
            BottomPickerUtils.showDatePicker(this, endTime, startTime, selectTime, myDatePickerCallBack);
        } else if (view.getId() == mTvCall.getId()) {

//            switch (infoBean.status) {
//                case "1":  // 待接单
//                    break;
//                case "2":  // 在路上
//                    break;
//                case "3":  // 洗车中
//                    break;
//                case "4":  //
//                    break;
//            }
            if ("1".equals(infoBean.status) || "2".equals(infoBean.status) || "3".equals(infoBean.status)) {
                Intent intent = new Intent(context, OrderDetalActivitiy.class);
                intent.putExtra(OrderDetalActivitiy.ORDERID, infoBean.id);
                startActivity(intent);
            } else {
                if (isNow) {
                    if (EmptyUtils.isEmpty(mTvAddress.getText().toString())) {
                        showToastMsg("请选择目的地");
                        return;
                    } else if (EmptyUtils.isEmpty(mTvCar.getText().toString())) {
                        showToastMsg("请选择车型");
                        return;
                    }
                } else {
                    if (EmptyUtils.isEmpty(mTvOrderTime.getText().toString())) {
                        showToastMsg("请选择时间");
                        return;
                    } else if (EmptyUtils.isEmpty(mTvOrderAdress.getText().toString())) {
                        showToastMsg("请选择目的地");
                        return;
                    } else if (EmptyUtils.isEmpty(mTvOrderCar.getText().toString())) {
                        showToastMsg("请选择车型");
                        return;
                    }
                }
//            Intent intent = new Intent(context, OrderInfoActivity.class);
//            intent.putExtra(OrderInfoActivity.ISNOW, isNow ? 1 : 2);
//            startActivity(intent);
                if (isNow) {// 现在约车
                    gotoOrder(nowCarId, getEditTextStr(et_fujia), postLong, postLati);
                } else {//  约车
                    gotoOrder(orderCarId, getEditTextStr(et_order_fujia), postLong, postLati);
                }
            }


        } else if (view.getId() == mTvAddress.getId() || view.getId() == mTvOrderAdress.getId()) {
            recyclerview.setVisibility(View.VISIBLE);
            searchEtInput.setVisibility(View.VISIBLE);
            rl_title.setVisibility(View.GONE);
            doSearchQuery(detailsPlace == null ? city : detailsPlace);
        } else if (view.getId() == mTvLocation.getId() || view.getId() == mIvLocation.getId()) {
            showProgressingDialog();
            getLocation();
        }
    }

    private void getQuesTion() {
        CommonSubscriber<CanShuBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                CanShuBean infoBean = (CanShuBean) o;
                Intent intent1 = new Intent(context, BaseUrlURLActivity.class);
                intent1.putExtra(BaseUrlURLActivity.MAIN_URL, infoBean.helpUrl);
                intent1.putExtra(BaseUrlURLActivity.TITILE, "帮助");
                context.startActivity(intent1);
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });


        GetsysparaMethods.getInstance().syspara(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID));
        rxManager.add(subscriber);
    }

    private void gotoOrder(int carId, String say, final String longitude, final String latitudu) {
        showProgressingDialog();
        CommonSubscriber<OrderIdBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
//                gotoActivity(MainActivity.class);
                OrderIdBean orderIdBean = (OrderIdBean) o;
                Intent intent = new Intent(context, OrderInfoActivity.class);
                intent.putExtra(OrderInfoActivity.ISNOW, isNow ? 1 : 2);
                intent.putExtra(OrderInfoActivity.ORDERIDBEAN, orderIdBean.id);
                intent.putExtra(OrderInfoActivity.LONGITUDE, longitude + "");
                intent.putExtra(OrderInfoActivity.LATITUDU, latitudu + "");
                intent.putExtra(OrderInfoActivity.REALLADRESS, reallAdress);
                startActivity(intent);

            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        GoOrderMethods.getInstance().addOrder(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID), reallAdress, carId, say, longitude, latitudu, isNow ? 1 : 2, time, isNow ? nowmoney : ordermoney, city);
        rxManager.add(subscriber);
    }

    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        if (rcode == 1000) {
            if (result != null && result.getQuery() != null) {             // 搜索poi的结果
                recyclerview.loadMoreComplete();
                recyclerview.refreshComplete();

                if (result.getQuery().equals(query)) {                     // 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();                        // 取得第一页的poiitem数据，页数从数字0开始
                    if (mIsRefreshOrLoadMore == 0) {
                        list.clear();
                        adapter.notifyDataSetChanged();
                    }

                    ArrayList<CityResultBean> list = new ArrayList<>();
                    if (poiItems != null && poiItems.size() > 0) {

                        if (mPageIndex == 0) {
                            CityResultBean address;
                            address = new CityResultBean("当前位置", current, null);
                            list.add(0, currentCityBean);
                        }

                        //清理之前搜索结果
                        for (PoiItem item : poiItems) {
                            CityResultBean address;
//                            address.setCity(DataUtil.cs(item.getCityName()));
//                            address.setProvince(DataUtil.cs(item.getProvinceName()));
//                            address.setCityShortName(DataUtil.cs(item.getAdName()) + DataUtil.cs(item.getTitle()));      //传入格式  区+位置名称
//                            address.setArea(DataUtil.cs(item.getAdName()));
//                            address.setAddress(DataUtil.cs(item.getTitle()));
//
//                            //传入格式  省+市+区+街道+门牌号
//                            address.setLatitude(item.getLatLonPoint().getLatitude());
//                            address.setLongitude(item.getLatLonPoint().getLongitude());
//                            address.setStreet(DataUtil.cs(item.getProvinceName()) + DataUtil.cs(item.getCityName()) +
//                                    DataUtil.cs(item.getAdName()) + DataUtil.cs(item.getSnippet()));
                            list.add(new CityResultBean(item.getTitle(), item.getProvinceName() + item.getCityName() + item.getAdName() + item.getSnippet(), item.getLatLonPoint()));
                        }
                        adapter.setDatas(list);
                    } else {
                        // 搜索无结果    全部类型搜索无结果则提示

//                        recyclerview.setVisibility(View.GONE);
//                        showToastMsg("搜索地点不存在");


                    }
                }
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
        String newText = s.toString().trim();
        if (!"".equals(newText)) {
            InputtipsQuery inputquery = new InputtipsQuery(newText, "");
            Inputtips inputTips = new Inputtips(this, inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == 1000) {
            final List<String> listString = new ArrayList<>();
            for (int i = 0; i < tipList.size(); i++) {
                listString.add(tipList.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<>(context, R.layout.item_fragment_map_list_result, listString);
            searchEtInput.setAdapter(aAdapter);
            searchEtInput.setThreshold(1);
            searchEtInput.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    showToastMsg(listString.get(i));
                    //message = listString.get(i);
                    KeyBordUtil.hideSoftKeyboard(searchEtInput);
                    keyword = listString.get(i);
//                    RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.SEARCH_KEY, listString.get(i)));
                    doSearchQuery(keyword);
                }
            });

            aAdapter.notifyDataSetChanged();
        }
    }

    private class MyDatePickerRepaymentDate implements BottomPickerUtils.DatePickerCallback {

        @Override
        public void onDateSelect(Calendar calendar) {
            int year = calendar.get(Calendar.YEAR);    //获取年
            int month = calendar.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            int day = calendar.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int min = calendar.get(Calendar.MINUTE);
            time = year + "-" + month + "-" + day + " " + hour + ":" + min;
            mTvOrderTime.setText(time);
            System.out.println(year + "----------" + month + "月" + day + "日" + hour + "时" + min + "分钟");
//            tvTime.setText(year + "年" + month + "月" + day + "日" + hour + "时" + min + "分");
//            sendtime = calendar.getTimeInMillis() / 1000 + "";
//            has_choose_time = true;
//            end_time = year+"."+month+"."+day;
        }
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnMarkerClickListener(this);
            setUpMap();
        }
        mSensorHelper = new SensorEventHelper(this);
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        // 设置默认定位按钮是否显示
        uiSettings = aMap.getUiSettings();
        //显示默认的定位按钮
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setZoomControlsEnabled(false);//隐藏放大 缩小 按钮
        // 可触发定位并显示当前位置
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.setOnCameraChangeListener(this);
    }

    private void getPermission() {
        //申请权限
        AndPermission.with(this)
                .requestCode(105)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.READ_PHONE_STATE)
                .rationale(mRationaleListener)
                .send();
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.setStatusBarColor(this, R.color.black);
    }


    @Override
    protected void setNavigation() {
        super.setNavigation();
        m_statusBar.setVisibility(View.GONE);
    }

    @PermissionYes(105)
    private void openPic() {
        LogUtils.e("成功回调了-->");
        getLocation();


    }

    @PermissionNo(105)
    private void injectPic() {
        LogUtils.e("失败回调了-->");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //申请权限
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能使用定位,拨打电话，请把权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };

    /**
     * 按两次返回键退出
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (keyCode == android.view.KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToastMsg("再按一次退出" + getString(R.string.app_name));
                exitTime = System.currentTimeMillis();
                return true;
            } else {
                onBackPressed();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    

  /*高德地图*******************开始/*/

    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        String snippet = marker.getSnippet();
        Log.d("snippet", snippet);
//        showToastMsg(snippet.toString());
        return true;
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            if (!mFirstFix) {
                mlocationClient.startLocation();
            }

        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        centerLatitude = cameraPosition.target.latitude;
        centerLongitude = cameraPosition.target.longitude;
        if (aMap != null) {
            aMap.clear();
        }
        gotoGetDots(centerLatitude + "", centerLongitude + "");
        //请求网络 获取数据
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
        //todo  后面加
        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constans.HASHID))) {
            gotoCheckOrder();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mapView.onPause();
        deactivate();
        mFirstFix = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                LatLng location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                double latitude = amapLocation.getLatitude(); //纬度
                double longitude = amapLocation.getLongitude();//经度
                city = amapLocation.getCity();
                detailsPlace = amapLocation.getStreet();
                keyword = amapLocation.getStreet();
                mTvLocation.setText(city);

                System.out.println("latitude" + latitude + "longitude" + longitude);
                //提交到网络请求数据
                aMap.clear();

                pullDataOnNet(latitude + "", longitude + "");
                mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                if (!mFirstFix) {
                    LocationUtils.setMapView(aMap, location);
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
                    mFirstFix = true;
                }

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
    /*            showToastMsg("定位失败");*/

            }
        }
    }

    //从网上拉去数据
    private void pullDataOnNet(String latitude, String longitude) {

        TestData testData = new TestData();
        testData.lat = Double.valueOf(latitude);
        testData.lng = Double.valueOf(longitude);
        LatLng latlng = new LatLng(testData.lat, testData.lng);
        addMarkersToMap(latlng);


/*        TestData testData1 = new TestData();
        testData.lat = 30.31472206;
        testData.lng = 120.33699799;
        LatLng latlng1 = new LatLng(testData.lat, testData.lng);
        addMarkersToMap(latlng1);*/


    }

    //网地图上添加mark
    private void addMarkersToMap(LatLng latlng) {

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.mipmap.wash_dot);
        Bitmap bitmap = ViewToBitmap.convertViewToBitmap(imageView);
        drawMarkerOnMap(latlng, bitmap);
    }

    //画图
    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon) {

        if (aMap != null && point != null) {

            Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
//                    .title(id)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
            return marker;

        }

        return null;


    }

    List<CityResultBean> list = new ArrayList<>();
    private CityResultBean currentCityBean = new CityResultBean();

    private void getLocation() {
        RxLocation.get().locateLastKnown(context)
                .subscribe(new LocationSubscriber() {
                    @Override
                    public void onLocatedSuccess(AMapLocation location) {
                        dismissProgressDialog();
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            currentCity = location.getCity();
                            city = location.getCity();
                            mTvLocation.setText(city);
                            current = location.getAddress();
                            currentCityBean.setDetail(location.getProvince() + location.getCity() + location.getDistrict() + location.getStreet());
                            currentCityBean.setArea(location.getCity());
                            currentCityBean.setProvince(location.getProvince());
                            currentCityBean.setCountry(location.getDistrict());
                            currentCityBean.setName(location.getPoiName());
                            doSearchQuery(keyword);

                            LocationUtils.moveCamera(new LatLng(location.getLatitude(), location.getLongitude()), aMap);
                            if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constans.HASHID))) {
                                gotoGetDots(location.getLatitude() + "", location.getLongitude() + "");
                            }
                        }
                    }

                    @Override
                    public void onLocatedFail(AMapLocation location) {
//                        ToastUtil.showToast(context, "定位失败");
                        dismissProgressDialog();
                    }
                });
    }

    private void doSearchQuery(String keyword) {

        if (!"".equals(keyword)) {
//             = false;
//            PageIndex = 0;
//            recyclerview.setSelection(0);
        }
        query = new PoiSearch.Query(keyword, poiSearchType, currentCity);    // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(mPageSize);                                     // 设置每页最多返回多少条poiitem
        query.setPageNum(0);
        // 设置查第一页
//        query.setCityLimit(true);

        LatLonPoint lp = new LatLonPoint(latitude, longitude);
        poiSearch = new PoiSearch(getActivity(), query);
        poiSearch.setOnPoiSearchListener(this);
        if ("".equals(keyword)) {
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 1000, true));
        }
        poiSearch.searchPOIAsyn();                                       // 异步搜索


    }

    //  去接口获取数据点点点
    private void gotoGetDots(String Latitude, String Longitude) {
        if (EmptyUtils.isEmpty(SPUtils.getShareString(Constans.HASHID))) {
            return;
        }
        CommonSubscriber<ArrayList<DotsInfoBean>> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                ArrayList<DotsInfoBean> list = (ArrayList<DotsInfoBean>) o;
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        pullDataOnNet(list.get(i).latitude, list.get(i).longitude);
                    }
                }
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
//                showToastMsg(e);
            }
        });

        GetDotsMethods.getInstance().shopinfo(subscriber, uid, hashid, Longitude, Latitude);
        rxManager.add(subscriber);
    }

}
